import {
  ProForm,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormTextArea,
  ProFormUploadDragger,
  stringify,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Spin, message } from 'antd';
import { useEffect, useState } from 'react';
import { crewSuperServices, pushSupersitionServices } from '../../services/supervisionApi';

/**
 * 通过 组长指定的 教室 组员只需要选定授课教室 就可以自动填入 授课班级 任课老师 授课节次 是获取当前时间计算的
 * @param
 * @returns
 */

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const [currentSession, setCurrentSession] = useState<string>();
  const [supersionData, setSupersionData] = useState<any>();
  const [filterSupersionData, setFilterSupersionData] = useState<any>();
  const [loading, setLoading] = useState<boolean>(true);

  const getCurrentSessionPeriod = () => {
    const now = new Date();
    const hour = now.getHours();
    const minutes = now.getMinutes();

    // 定义各大节课的时间段
    const sessionPeriods = [
      { start: 8 * 60 + 20, end: 10 * 60, value: '1-2', label: '第一大节' },
      { start: 10 * 60 + 15, end: 11 * 60 + 55, value: '3-4', label: '第二大节' },
      { start: 14 * 60 + 0, end: 15 * 60 + 45, value: '5-6', label: '第三大节' },
      { start: 16 * 60 + 0, end: 17 * 60 + 45, value: '7-8', label: '第四大节' },
      { start: 19 * 60 + 0, end: 20 * 60 + 45, value: '9-10', label: '第五大节' },
    ];

    const currentTimeInMinutes = hour * 60 + minutes;

    for (const period of sessionPeriods) {
      if (currentTimeInMinutes >= period.start && currentTimeInMinutes <= period.end) {
        return period.value;
      }
    }
    return undefined;
  };

  // 获取组员的督导数据
  const getCrewSuperData = useRequest(crewSuperServices, {
    manual: true,
    onSuccess: (data) => {
      setLoading(false);
      setSupersionData(data);
    },
    onError: (error) => {
      message.error(stringify(error));
    },
    onFinally: () => {
      setLoading(false);
    },
  });

  // useEffect 生命周期
  useEffect(() => {
    getCrewSuperData.run();
  }, []);

  return (
    <Spin spinning={loading}>
      <ProForm
        onFinish={async (values) => {
          console.log(values);
          const result = supersionData.filter(
            (item: COURSE.CourseListItem) => item.classroomLocation === values.classroomLocation,
          );
          values.courseId = result[0].id;
          values.upload = values.upload ? values.upload?.map((item: any) => item.response.data) : [];
          try {
            //
            if (!values.breakfast) values.breakfast = 0;
            if (!values.clothing) values.clothing = 0;
            if (!values.snack) values.snack = 0;
            if (!values.badBehaviorRemark) values.badBehaviorRemark = '无';
            if (!values.lookUp) values.lookUp = '否';
            if (!values.interaction) values.interaction = '否';
            if (!values.behaviorRemark) values.behaviorRemark = '无';
            await pushSupersitionServices(values);
            // await pushDingDingServices(values);

            // message.success('真棒，又完成一个小任务了...');
            location.reload();
          } catch (error) {
            // 处理错误
            console.error('接口调用失败:', error);
            message.error('提交失败，请稍后再试...');
          }
        }}
        initialValues={{
          session: getCurrentSessionPeriod(),
        }}
      >
        <ProFormSelect
          options={[
            {
              value: '1-2',
              label: '第一大节',
            },
            {
              value: '3-4',
              label: '第二大节',
            },
            {
              value: '5-6',
              label: '第三大节',
            },
            {
              value: '7-8',
              label: '第四大节',
            },
            {
              value: '9-10',
              label: '第五大节',
            },
          ]}
          width="md"
          name="session"
          label={'授课节次'}
        />
        <>
          {supersionData ? (
            <ProFormSelect
              name="classroomLocation"
              label={'授课教室'}
              width="md"
              request={() => {
                return supersionData.map((item: COURSE.CourseListItem) => {
                  return {
                    label: item.classroomLocation,
                    value: item.classroomLocation,
                  };
                });
              }}
            />
          ) : null}
        </>

        <ProFormDependency name={['classroomLocation']}>
          {({ classroomLocation }) => {
            return (
              <ProFormSelect
                name="classNumber"
                label={'授课班级'}
                width="md"
                dependencies={['classroomLocation']}
                request={(params) => {
                  return supersionData
                    .filter(
                      (item: COURSE.CourseListItem) =>
                        item.classroomLocation === params.classroomLocation,
                    )
                    .map((item: COURSE.CourseListItem) => {
                      return {
                        label: item.classNumber,
                        value: item.classNumber,
                      };
                    });
                }}
              />
            );
          }}
        </ProFormDependency>

        <ProFormDependency name={['classroomLocation']}>
          {({ classroomLocation }) => {
            return (
              <ProFormSelect
                name="instructor"
                label={'任课教师'}
                width="md"
                dependencies={['classroomLocation']}
                request={async (params) => {
                  return supersionData
                    .filter(
                      (item: COURSE.CourseListItem) =>
                        item.classroomLocation === params.classroomLocation,
                    )
                    .map((item: COURSE.CourseListItem) => {
                      return {
                        label: item.instructor,
                        value: item.instructor,
                      };
                    });
                }}
              />
            );
          }}
        </ProFormDependency>
        <ProFormUploadDragger
          label="上传图像"
          name="upload"
          action="/api/crew/uploadPhoto"
          fieldProps={{
            name: 'file',
            style: { maxWidth: '350px' },
            beforeUpload: (file, fileList) => {
              if (file.type === 'image/jpeg' || file.type === 'image/png') {
                return true;
              } else {
                new Error('只支持 JPEG 和 PNG 格式的图片');
                return false;
              }
            },
          }}
        />

        {/* 不良行为 */}
        <ProFormDigit
          name="breakfast"
          label="早餐携带人数"
          placeholder="0"
          width="md"
          required
          min={0}
          max={1000000}
          // fieldProps={}
        />

        <ProFormDigit
          name="clothing"
          label="着装不规范人数"
          placeholder="0"
          width="md"
          required
          // fieldProps={}
        />

        <ProFormDigit
          name="snack"
          label="水果、零食等携带人数"
          placeholder="0"
          width="md"
          required
          // fieldProps={}
        />

        <ProFormTextArea
          name="badBehaviorRemark"
          label="其他不良行为"
          placeholder={'无'}
          width="md"
          required
        />

        {/* 优良行为 */}
        <ProFormSwitch name="lookUp" label="抬头率高" />

        <ProFormSwitch name="interaction" label="师生互动率高" />

        <ProFormTextArea
          name="behaviorRemark"
          label="其他优良行为"
          placeholder={'无'}
          width="md"
          required
        />
      </ProForm>
    </Spin>
  );
};
